package db_main

import (
	"fmt"
	"gorm.io/gorm"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
)

func GetUserLotteryHistoryParam(param map[string]interface{}, page, size int) ([]models_main.UserLotteryHistory, error) {
	fName := "GetUserLotteryHistoryParam"
	var o []models_main.UserLotteryHistory
	table := mysql.GetRTable(&models_main.UserLotteryHistory{})
	mysql.Condition(table, param, "", "draw_time desc", page, size)
	err := table.Find(&o).Error
	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, err
}

func GetUserLotteryHistoryById(uid int, page, size int) ([]models_main.UserLotteryHistory, error) {
	fName := "GetUserLotteryHistoryById"
	var o []models_main.UserLotteryHistory
	err := mysql.GetRTable(&models_main.UserLotteryHistory{}).
		Where("uid = ?", uid).
		Order("draw_time desc").
		Limit(size).
		Offset((page - 1) * size).
		Find(&o).Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return o, nil
}

func InsertUserLotteryHistoryByTransactions(session *gorm.DB, history *models_main.UserLotteryHistory) error {
	fName := "InsertUserLotteryHistoryByTransactions"
	err := session.Create(history).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}

func UpdateUserLotteryHistoryByTransactions(session *gorm.DB, columns []string, history *models_main.UserLotteryHistory) error {
	fName := "UpdateUserLotteryHistoryByTransactions"
	err := session.
		Select(columns).
		Updates(history).Error
	if err != nil {
		session.Rollback()
		return fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	return nil
}
